<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>首页</title>
	<%
		pageContext.setAttribute("APP_PATH", request.getContextPath());
	%>
	<!-- 引入jQuery -->
	<script type="text/javascript" src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
	<!-- 引入Bootstrap(依赖jquery) -->
	<link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
	<script src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

	<!-- Modal -->
	<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="empUpdateModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title">员工修改</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<div class="form-group">
							<label class="col-sm-2 control-label">empName</label>
							<div class="col-sm-10">
								<p class="form-control-static" name="empName" id="empName_update_static"></p>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">email</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="email" id="email_update_input" placeholder="email@atguigu.com">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">gender</label>
							<div class="col-sm-10">
								<label class="radio-inline">
									<input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked">男
								</label>
								<label class="radio-inline">
									<input type="radio" name="gender" id="gender2_update_input" value="F">女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">deptName</label>
							<div class="col-sm-4">
								<select class="form-control" name="dId"></select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
				</div>
			</div>
		</div>
	</div>
	
	<!-- Modal -->
	<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="empAddModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">员工添加</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<div class="form-group">
							<label class="col-sm-2 control-label">empName</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="empName" id="empName_add_input" placeholder="empName">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">email</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="email" id="email_add_input" placeholder="email@atguigu.com">
								<span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">gender</label>
							<div class="col-sm-10">
								<label class="radio-inline">
									<input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked">男
								</label>
								<label class="radio-inline">
									<input type="radio" name="gender" id="gender2_add_input" value="F">女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">deptName</label>
							<div class="col-sm-4">
								<select class="form-control" name="dId"></select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
				</div>
			</div>
		</div>
	</div>

	<div class="container">
		<div class="row">
			<div class="col-md-12">
				<h1>SSM-CRUD</h1>
			</div>
		</div>
		<div class="row">
			<div class="col-md-4 col-md-offset-8">
				<button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
				<button class="btn btn-danger" id="emp_delete_all_btn">删除</button>
			</div>
		</div>
		<div class="row">
			<div class="col-md-12">
				<table class="table table-hover" id="emps_table">
					<thead>
						<tr>
							<th><input type="checkbox" id="check_all"></th>
							<th>#</th>
							<th>empName</th>
							<th>gender</th>
							<th>email</th>
							<th>deptName</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>
		</div>
		<div class="row">
			<div class="col-md-6" id="page_info_area"></div>
			<div class="col-md-6" id="page_nav_area">
				<%-- <nav aria-label="Page navigation">
					<ul class="pagination">
						<li><a href="${APP_PATH }/emps?pn=1">首页</a></li>
						<c:if test="${pageInfo.hasPreviousPage }">
							<li><a href="${APP_PATH }/emps?pn=${pageInfo.pageNum - 1}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>
						</c:if>
						<c:forEach items="${pageInfo.navigatepageNums }" var="page_num">
							<c:if test="${page_num == pageInfo.pageNum }">
								<li class="active"><a href="#">${page_num }</a></li>
							</c:if>
							<c:if test="${page_num != pageInfo.pageNum }">
								<li><a href="${APP_PATH }/emps?pn=${page_num}">${page_num }</a></li>
							</c:if>
						</c:forEach>
						<c:if test="${pageInfo.hasNextPage }">
							<li><a href="${APP_PATH }/emps?pn=${pageInfo.pageNum + 1 }" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>
						</c:if>
						<li><a href="${APP_PATH }/emps?pn=${pageInfo.pages }">末页</a></li>
					</ul>
				</nav> --%>
			</div>
		</div>
	</div>
	
	<script type="text/javascript">
		var totalRecord = 0, currentNum = 0;
		
		$(function() {
			to_page(1);
		});
		
		function to_page(pn) {
			$.ajax({
				url: "${APP_PATH}/emps",
				data: "pn=" + pn,
				type: "GET",
				success: function(result) {
					console.log(result);
					build_emps_table(result);
					build_page_info(result);
					build_page_nva(result);
				}
			});
		}
		
		function build_emps_table(result) {
			$("#emps_table tbody").empty();
			var emps = result.data.pageInfo.list;
			$.each(emps, function(index, item) {
				//console.log(index);
				console.log(item);
				var checkBoxTd = $("<td></td>").append($("<input type='checkbox' class='check-item'/>"));
				var empIdTd = $("<td></td>").append(item.empId);
				var empNameTd = $("<td></td>").append(item.empName);
				var genderTd = $("<td></td>").append(item.gender=='M' ? '男' : '女');
				var emailTd = $("<td></td>").append(item.email);
				var deptNameTd = $("<td></td>").append(item.department.deptName);
				var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
						.append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append('编辑');
				editBtn.attr("edit-id", item.empId);
				var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
						.append($("<span></span>").addClass("glyphicon glyphicon-trash")).append('删除');
				deleteBtn.attr("delete-id", item.empId);
				var btnTd = $("<td></td>").append(editBtn).append(" ").append(deleteBtn);
				$("<tr></tr>").append(checkBoxTd)
						.append(empIdTd)
						.append(empNameTd)
						.append(genderTd)
						.append(emailTd)
						.append(deptNameTd)
						.append(btnTd)
						.appendTo("#emps_table tbody");
			});
		}
		
		function build_page_info(result) {
			$("#page_info_area").empty();
			var pageInfo = result.data.pageInfo;
			$("#page_info_area").append("当前第" + pageInfo.pageNum + "页，共" + pageInfo.pages + "页，总" + pageInfo.total + "条记录");
			totalRecord = pageInfo.total;
			currentNum = pageInfo.pageNum;
		}
		
		function build_page_nva(result) {
			$("#page_nav_area").empty();
			var ul = $("<ul></ul>").addClass("pagination");
			var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
			var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;").attr("href", "#"));
			if (result.data.pageInfo.hasPreviousPage == false) {
				firstPageLi.addClass("disabled");
				prePageLi.addClass("disabled");
			} else {
				firstPageLi.click(function() {
					to_page(1);
				});
				prePageLi.click(function() {
					to_page(result.data.pageInfo.pageNum - 1);
				});
			}
			ul.append(firstPageLi).append(prePageLi);
			
			var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;").attr("href", "#"));
			var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
			if (result.data.pageInfo.hasNextPage == false) {
				nextPageLi.addClass("disabled");
				lastPageLi.addClass("disabled");
			} else {
				nextPageLi.click(function() {
					to_page(result.data.pageInfo.pageNum + 1);
				});
				lastPageLi.click(function() {
					to_page(result.data.pageInfo.pages);
				});
			}
			
			$.each(result.data.pageInfo.navigatepageNums, function(index, item) {
				var numLi = $("<li></li>").append($("<a></a>").append(item));
				if (result.data.pageInfo.pageNum == item) {
					numLi.addClass("active");
				}
				numLi.click(function() {
					to_page(item);
				});
				ul.append(numLi);
			})
			ul.append(nextPageLi).append(lastPageLi);
			var navEle = $("<na></na>").append(ul);
			navEle.appendTo("#page_nav_area");
		}
		
		function reset_form(ele) {
			$(ele)[0].reset();
			$(ele).find("*").removeClass("has-success has-error");
			$(ele).find(".help-block").text("");
		}
		
		$("#emp_add_modal_btn").click(function() {
			//$("#empAddModal form")[0].reset();
			reset_form("#empAddModal form");
			getDepts("#empAddModal select");
			$("#empAddModal").modal({
				backdrop: 'static'
			});
		});
		
		function getDepts(ele) {
			$(ele).empty();
			$.ajax({
				url: "${APP_PATH}/depts",
				type: "GET",
				success: function(result) {
					console.log(result);
					$.each(result.data.depts, function() {
						var optionEle = $("<option></option>").append(this.deptName).attr("value", this.deptId);
						optionEle.appendTo(ele);
					});
				}
			});
		}
		
		function validate_add_form() {
			var empName = $("#empName_add_input").val();
			var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
			if(!regName.test(empName)) {
				//alert("用户名可以是2-5位中文或6-16位英文和数字的组合");
				show_validate_msg("#empName_add_input","error","用户名可以是2-5位中文或6-16位英文和数字的组合");
				return false;
			} else {
				show_validate_msg("#empName_add_input","success","");
			}
			var email = $("#email_add_input").val();
			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
			if (!regEmail.test(email)) {
				//alert("邮箱格式不正确！");
				show_validate_msg("#email_add_input","error","邮箱格式不正确！");
				return false;
			} else {
				show_validate_msg("#email_add_input","success","");
			}
			return true;
		}
		
		function show_validate_msg(ele,status,msg) {
			$(ele).parent().removeClass("has-success has-error");
			$(ele).next("span").text("");
			if ("success" == status) {
				$(ele).parent().addClass("has-success");
				$(ele).next("span").text(msg);
			} else if ("error" == status) {
				$(ele).parent().addClass("has-error");
				$(ele).next("span").text(msg);
			}
		}
		
		$("#empName_add_input").change(function() {
			var empName = this.value;
			console.log(empName);
			$.ajax({
				url: "${APP_PATH}/checkuser",
				data: "empName=" + empName,
				type: "POST",
				success: function(result) {
					if (result.code == 100) {
						show_validate_msg("#empName_add_input","success","用户名可用");
						$("#emp_save_btn").attr("ajax-va", "success");
					} else {
						show_validate_msg("#empName_add_input","error",result.data.va_msg);
						$("#emp_save_btn").attr("ajax-va", "error");
					}
				}
			});
		});
		
		$("#emp_save_btn").click(function() {
			if(!validate_add_form()) {
				return false;
			}
			if ($(this).attr("ajax-va") == "error") {
				return false;
			}
			//alert($("#empAddModal form").serialize());
			$.ajax({
				url: "${APP_PATH}/emp",
				type: "POST",
				data: $("#empAddModal form").serialize(),
				success: function(result) {
					console.log(result);
					if (result.code == 100) {
						$("#empAddModal").modal('hide');
						to_page(totalRecord);
					} else {
						if (result.data.errorFields.empName) {
							show_validate_msg("#email_add_input","error",result.data.errorFields.empName);
						}
						if (result.data.errorFields.email) {
							show_validate_msg("#email_add_input","error",result.data.errorFields.email);
						}
					}
				}
			});
		});
		
		$(document).on("click", ".edit_btn", function() {
			//alert("edit");
			getDepts("#empUpdateModal select");
			//console.log('----' + $(this).attr("edit-id"));
			getEmp($(this).attr("edit-id"));
			$("#emp_update_btn").attr("update-id",$(this).attr("edit-id"));
			$("#empUpdateModal").modal({
				backdrop: "static"
			});
		});
		
		function getEmp(id) {
			$.ajax({
				url: "${APP_PATH}/emp/" + id,
				type: "GET",
				success: function(result) {
					//console.log(result);
					var empData = result.data.emp;
					$("#empName_update_static").text(empData.empName);
					$("#email_update_input").val(empData.email);
					$("#empUpdateModal input[name=gender]").val([empData.gender]);
					$("#empUpdateModal select").val([empData.dId]);
				}
			});
		}
		
		$("#emp_update_btn").click(function() {
			var email = $("#email_update_input").val();
			console.log(email);
			var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
			if (!regEmail.test(email)) {
				//alert("邮箱格式不正确！");
				show_validate_msg("#email_update_input","error","邮箱格式不正确！");
				return false;
			} else {
				show_validate_msg("#email_update_input","success","");
			}
			/* $.ajax({
				url: "${APP_PATH}/emp/" + $(this).attr("update-id"),
				//url: "${APP_PATH}/emp",
				type: "POST",
				data: $("#empUpdateModal form").serialize() + "&_method=PUT",
				success: function(result) {
					console.log(result);
				}
			}); */
			$.ajax({
				url: "${APP_PATH}/emp/" + $(this).attr("update-id"),
				type: "PUT",
				data: $("#empUpdateModal form").serialize(),
				success: function(result) {
					console.log(result);
					$("#empUpdateModal").modal("hide");
					to_page(currentNum);
				}
			});
		});
		
		$(document).on("click", ".delete_btn", function() {
			var empName = $(this).parents("tr").find("td:eq(2)").text();
			var empId = $(this).attr("delete-id");
			//alert(empName + " " + empId);
			if (confirm("确认删除【" + empName + "】吗？")) {
				$.ajax({
					url: "${APP_PATH}/emp/" + empId,
					type: "DELETE",
					success: function(result) {
						if (result.code == 100) {
							to_page(currentNum);
						}
					}
				});
			}
		});
		
		$("#check_all").click(function() {
			//alert($(this).attr("checked"));
			$(".check-item").prop("checked", $(this).prop("checked"));
		});
		
		$(document).on("click", ".check-item", function() {
			var flag = $(".check-item:checked").length == $(".check-item").length
			$("#check_all").prop("checked", flag);
		});
		
		$("#emp_delete_all_btn").click(function() {
			var empNames = "";
			var del_idstr = "";
			$.each($(".check-item:checked"), function() {
				empNames += $(this).parents("tr").find("td:eq(2)").text() + "，";
				del_idstr += $(this).parents("tr").find("td:eq(1)").text() + "-";
			});
			empNames = empNames.substring(0, empNames.length - 1);
			del_idstr = del_idstr.substring(0, del_idstr.length - 1);
			if (confirm("确定删除【" + empNames + "】吗")) {
				$.ajax({
					url: "${APP_PATH}/emp/" + del_idstr,
					type: "DELETE",
					success: function(result) {
						alert(result.msg);
						to_page(currentNum);
					}
				});
			}
		});
	</script>
	
</body>
</html>
